ActiveAdmin.register Payroll do
  filter :coach_name
  filter :coach_kind, as: :string, label: '教练类型'
  filter :company_name
  filter :store_name
  filter :course_name
  filter :class_start_time

  actions :index

  action_item :report, only: :index do
    render partial: 'report'
  end

  index do
    column :id
    column :timetable_id
    column :coach_name
    column :coach_employee_id
    column '教练类型' do |c|
      c.coach.kind
    end
    column :company_name
    column :city
    column :store_name
    column :course_name
    column :class_start_time
    column :class_end_time
    column :price
    column :market_price
    column :member_price
    column :t_status_i18n
    column :salary
    column :status_i18n
    column :updated_at
  end

  controller do
    def scoped_collection
      Payroll.includes(:course, :coach)
    end

    def recalculate
      coaches = params[:payroll][:coach_id]
      coaches.delete("-1")
      (coaches.blank? ? Coach.pluck(:id) : coaches.map(&:to_i)).group_by { |id| id % 25 }.values.each { |value|
        SalaryJob.set(wait: 1.seconds).perform_later(params[:payroll][:company_id], value, params[:payroll][:class_start_time], params[:payroll][:class_end_time])
      }
      redirect_to collection_path, notice: '您选择用户的工资已开始计算,请稍后查看'
    end

    def index
      if params[:format].eql?("csv") || params[:format].eql?("xls")
        sql = Payroll.ransack(params[:q]).result.to_sql
        filter = sql.split("WHERE")[1]
        csv = CSV.generate(headers: true) do |row|
          row << %w{课表编号 教练编号 教练 工号 教练类型 集团编号 集团 城市 门店编号 门店 收费类型 课程分类 课程编号 课程 上课时间 下课时间 时长 价格 市场价 会员价 剩余名额 会员预约 开放名额 非会员预约 登记人数 巡查人数 基础人数 排队人数 渠道预约 课表状态 版权费 课时费 补贴 工资 实付工资 基础课时费 经理扣款 经理扣款原因 巡查扣款 登记扣款 迟到扣款 旷课扣款 包课费用 应发 状态 签到时间 计算时间}
          Payroll.joins(:course, :coach).where(filter).pluck(
            Arel.sql(
              "payrolls.timetable_id, coaches.id, coaches.name, coaches.employee_id, coaches.kind, payrolls.company_id, payrolls.company_name, payrolls.city, payrolls.store_id, payrolls.store_name,
                '{\"0\": \"免费课\",\"1\": \"收费课\",\"2\": \"GX-收费课\",\"3\": \"PT-收费课\",\"4\": \"线上课\"}'::jsonb -> courses.usage::text, courses.category, courses.id, payrolls.course_name, payrolls.class_start_time, payrolls.class_end_time,
                EXTRACT(EPOCH from (payrolls.class_end_time - payrolls.class_start_time))/60, payrolls.price, payrolls.market_price, payrolls.member_price, payrolls.quota, payrolls.m_quota, (payrolls.quota + payrolls.m_quota + payrolls.nm_quota),
                payrolls.nm_quota, payrolls.r_quota, payrolls.i_quota, payrolls.b_quota, payrolls.q_quota, payrolls.c_quota, '{\"4\": \"已发布\",\"5\": \"已签到\",\"6\": \"迟到\",\"7\": \"旷课\"}'::jsonb -> payrolls.t_status::text, payrolls.cr_fee, payrolls.cl_fee, CASE courses.usage WHEN 0 THEN payrolls.subsidy ELSE 0 END,
                payrolls.salary,  CASE courses.usage WHEN 0 THEN 0 ELSE payrolls.subsidy END, payrolls.deduction,'{\"-1\": \"已拒绝\",\"0\": \"待确认\",\"1\": \"已确认\"}'::jsonb->payrolls.status::text, to_char(payrolls.updated_at,'YYYY-MM-DD HH24:MI:SS'),to_char(payrolls.created_at,'YYYY-MM-DD HH24:MI:SS')
              ")
          ).each do |data|
            deduction = data.delete_at(-4)
            salary = data[33]
            #基础课时费
            basic = deduction.detect { |item| item["type"].eql?("basic") } || {}
            data.insert(-4, basic.fetch("amount", 0).to_d.eql?(0) ? '' : -basic.fetch("amount", 0).to_d)
            #经理扣款
            other = deduction.detect { |item| item["type"].eql?("other") } || {}
            data.insert(-4, other.fetch("amount", ""))
            data.insert(-4, other.fetch("reason", ""))
            #迟到|旷课|包课
            %w{inspector attendance late absent standard}.each { |col|
              _data = deduction.detect { |item| item["type"].eql?(col) } || {}
              data.insert(-4, _data.fetch("amount", ""))
            }
            dc_amount = deduction.map { |item| item.fetch("amount", 0).to_d }.sum
            data.insert(-4, salary - dc_amount)
            row << data
          end
        end
        send_data(("\uFEFF" + +csv), type: Mime[:csv], disposition: "attachment; filename=payrolls-#{Time.current.to_i}.csv")
      else
        index!
      end
    end
  end
end
